package deadlock;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Brook
 *
 * use tryLock来避免死锁
 */
public class TryLockDeadLock implements Runnable{

    int flag = 1;
    static Lock lock1 = new ReentrantLock();
    static Lock lock2 = new ReentrantLock();

    public static void main(String[] args) {
        TryLockDeadLock tryLockDeadLock1 = new TryLockDeadLock();
        TryLockDeadLock tryLockDeadLock2 = new TryLockDeadLock();
        tryLockDeadLock1.flag=1;
        tryLockDeadLock2.flag=0;
        new Thread(tryLockDeadLock1).start();
        new Thread(tryLockDeadLock2).start();
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            if (flag == 1) {
                try {
                    if (lock1.tryLock(800, TimeUnit.MILLISECONDS)) {
                        Thread.sleep(new Random().nextInt(1000));
                        if(lock2.tryLock(800, TimeUnit.MILLISECONDS)){
                            System.out.println(Thread.currentThread().getName()+"成功获取了两把锁");
                            lock2.unlock();
                            lock1.unlock();
                            break;
                        }else{
                            System.out.println(Thread.currentThread().getName()+"获取锁lock2失败,已重试");
                            lock1.unlock();
                            Thread.sleep(new Random().nextInt(1000));
                        }
                    }else {
                        System.out.println(Thread.currentThread().getName()+"获取锁lock1失败，已重试");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if (flag == 0) {
                try {
                    if (lock2.tryLock(800, TimeUnit.MILLISECONDS)) {
                        Thread.sleep(new Random().nextInt(1000));
                        if(lock1.tryLock(800, TimeUnit.MILLISECONDS)){
                            System.out.println(Thread.currentThread().getName()+"成功获取了两把锁");
                            lock1.unlock();
                            lock2.unlock();
                            break;
                        }else{
                            System.out.println(Thread.currentThread().getName()+"获取锁lock1失败,已重试");
                            lock2.unlock();
                            Thread.sleep(new Random().nextInt(1000));
                        }
                    }else {
                        System.out.println(Thread.currentThread().getName()+"获取锁lock2失败，已重试");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
